package task

import (
	"time"

	"gitee.com/sansaniot/ssiot-core/facade/env"

	"ssadmin/common/constant"
	dto "ssadmin/common/query"
	"ssadmin/common/utils"
	"ssadmin/internal/admin/models"
)

// UserStatTask 用户数、活跃用户数统计
func UserStatTask() {
	userModel := &models.User{}
	userModel.Orm = env.Db
	userList := make([]models.User, 0)
	_ = userModel.Model.FindList(&userList)
	if len(userList) == 0 {
		return
	}
	sysLogModel := &models.SysLog{}
	sysLogModel.Orm = env.Db
	tmpMapArr := make([]map[string]interface{}, 0)
	now := time.Now()
	nowTime := utils.ConvtTimeToStr(now, utils.TIME_FMT_FULL)
	beforeTime := utils.ConvtTimeToStr(now.Add(-10*time.Minute), utils.TIME_FMT_FULL)
	env.Db.Raw("SELECT distinct(username) FROM \"sys_operate_log\" WHERE \"operate_time\" >= ? and \"operate_time\" <= ?", beforeTime, nowTime).Scan(&tmpMapArr)

	// 按创建人的用户数
	creatorUserCnt := make(map[string]int)
	// 用户名-id map
	userMap := make(map[string]string)
	// 按用户id的活跃用户数
	userActiveCnt := make(map[string]int)
	for _, u := range userList {
		if len(u.CreatorId) == 0 {
			continue
		}
		creatorUserCnt[u.CreatorId]++
		userMap[u.Username] = u.UserId
	}
	// 活跃用户名转换
	for _, m := range tmpMapArr {
		userId, ok := userMap[m["username"].(string)]
		if !ok {
			continue
		}
		userActiveCnt[userId] = 1
	}
	// 用户数
	sysDataDetailModel := &models.SysDataDetail{}
	sysDataDetailModel.Orm = env.Db
	for creatorId, cnt := range creatorUserCnt {
		if err := sysDataDetailModel.Add(&models.SysDataDetail{
			Type:       constant.TypeOfUserCount,
			Key:        creatorId,
			Value:      cnt,
			CreateTime: dto.LocalTime(time.Now()),
		}); err != nil {
			env.Log.Error(err)
		}
	}
	// 活跃记录
	for userId, cnt := range userActiveCnt {
		if err := sysDataDetailModel.Add(&models.SysDataDetail{
			Type:       constant.TypeOfUserActiveCount,
			Key:        userId,
			Value:      cnt,
			CreateTime: dto.LocalTime(time.Now()),
		}); err != nil {
			env.Log.Error(err)
		}
	}
}
